package com.yzf.zyfverifycode;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopeer.cardstack.CardStackView;
import com.yzf.zyfverifycode.manager.LoginManager;
import com.yzf.zyfverifycode.utils.HttpXUtils;
import com.yzf.zyfverifycode.utils.IPUtils;
import com.yzf.zyfverifycode.utils.Utils;
import com.yzf.zyfverifycode.utils.log.LogcatFileManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.util.Arrays;
import java.util.Random;

import static com.yzf.zyfverifycode.Constants.TAG;
import static com.yzf.zyfverifycode.Constants.isSan;
import static com.yzf.zyfverifycode.Constants.simArray;
import static com.yzf.zyfverifycode.Constants.verisonCode;
import static com.yzf.zyfverifycode.Constants.versionName;

/**
 * 项目名称：FoldingVerifyCode
 * 类描述：短信猫主类
 * 创建人：Administrator
 * 创建时间：2019年10月1日
 */
public class CardStackActivity extends Activity implements CardStackView.ItemExpendListener {

    private LinearLayout mActionButtonContainer;
    private CardStackView cardStackView;
    private CardAdapter cardAdapter;
    public static boolean isStart = false;
    private Boolean firstBoo = true;

    private UrlDialog urlDialog;
    public static String deviceid = "";
    public static String androidId = "";
    private TextView versionTv;
    private static String[] permissions = {Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.READ_SMS,
            Manifest.permission.INTERNET,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //    public static Integer[] DATAS = new Integer[]{
    //            R.color.color_12,
    //            R.color.color_13,
    //            R.color.color_14
    //    };
    public static Integer[] DATAS;
    private TelDialog telDialog;
    private long mExitTime = 0;
    @SuppressLint("HandlerLeak")
    private Handler UrlHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            CardStackActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (urlDialog != null && urlDialog.isShowing()) {
                        urlDialog.dismiss();
                    }
                    CardStackActivity.this.recreate();
                }
            });
        }
    };

    private Integer[] getDATAS() {
        Integer[] colors;
        int seed = randomBySeed();
        int color1 = this.getResources().getIdentifier("color_" + (seed + 1), "color", this.getPackageName());
        int color2 = this.getResources().getIdentifier("color_" + (seed + 2), "color", this.getPackageName());
        int color3 = this.getResources().getIdentifier("color_" + (seed + 3), "color", this.getPackageName());

        colors = new Integer[]{color1, color2, color3};
        return colors;
    }

    private Integer randomBySeed() {
        Random random = new Random();
        int seed = random.nextInt(23);
        Log.d(TAG, "randomBySeed = " + seed);
        return seed;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        // 判断本地保存的值是否为空 为空从新输入
        if (TextUtils.isEmpty(IPUtils.getOutNetIP(this))) {
            Log.d(TAG, "IPUtils.getOutNetIP===null");
            if (!urlDialog.isShowing()) {
                urlDialog.show();
            }
        } else {
            try {
                initPhoneSP();
                activityLogin();
                if (firstBoo) {
                    activityFindBackInfo();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.d(TAG, "---------------------------------------------------onConfigurationChanged");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (Constants.isSan) {
            Constants.sanPhoneNo1 = "";
            Constants.sanPhoneNo2 = "";
        }
        try {
            initPhoneSP();
            //            activityFindBackInfo();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isStart = false;
        closeTelDialog();
        Log.d(TAG, "---------------onPause--------------------");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Constants.sanPhoneNo1 = "";
        Constants.sanPhoneNo2 = "";
        Log.d(TAG, "----------------onStop-----------------------");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UrlHandler.removeCallbacksAndMessages(null);
        try {
            LogcatFileManager.getInstance().stopLogcatManager();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(TAG, "----------------onDestroy--------------------");

    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //        CrashReport.initCrashReport(getApplicationContext(), "85e455b2b8", true);
        x.Ext.init(getApplication());
        x.Ext.setDebug(false);
        DATAS = getDATAS();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        verisonCode = Utils.getVersionCode(this) + "";
        versionName = Utils.getVerName(this);

        try {
            LogcatFileManager.getInstance().startLogcatManager(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        isStart = true;
        if (!TextUtils.isEmpty(Utils.getDeviceBrand()) && Utils.getDeviceBrand().toLowerCase().equals("samsung")) {
            Constants.isSan = true;
        }
        //去除title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //去掉Activity上面的状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.card_stack_layout);
        mActionButtonContainer = findViewById(R.id.button_container);
        mActionButtonContainer.setVisibility(View.GONE);

        cardStackView = this.findViewById(R.id.cardStackView);
        cardAdapter = new CardAdapter(this);
        cardStackView.setAdapter(cardAdapter);
        cardStackView.setItemExpendListener(this);
        versionTv = this.findViewById(R.id.version_info_mainpage_tv);
        versionTv.setText("V" + versionName);
        SMSReceiver smsBroadCastReceiver = new SMSReceiver(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(smsBroadCastReceiver, filter);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                for (int i : DATAS) {
                    Log.d(TAG, "DATAS ===> " + i);
                }
                cardAdapter.updateData(Arrays.asList(DATAS));
            }
        }, 200);
        urlDialog = new UrlDialog(this, UrlHandler, "");
    }

    public void requestPermission() {
        int agreedCount = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            // 检查该权限是否已经获取
            for (String permission : permissions) {
                int i = ContextCompat.checkSelfPermission(this, permission);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                Log.d(TAG, "checkSelfPermission = " + permission + "------status-------" + i);
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
                    showDialogTipUserRequestPermission();
                } else {
                    agreedCount++;
                }
            }
            Log.d(TAG, "-------------------agreedCount----------------=" + agreedCount);
        }
    }

    public void onPreClick(View view) {
        cardStackView.pre();
    }

    public void onNextClick(View view) {
        cardStackView.next();
    }

    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {

        AlertDialog.Builder dialogTipUserRequestPermissionBuilder = new AlertDialog.Builder(this)
                .setTitle("读取短信权限不可用")
                .setMessage("由于app要获取短信内容；\n否则，您将无法正常使用app")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startRequestPermission();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false);
        if (dialogTipUserRequestPermissionBuilder != null) {
            dialogTipUserRequestPermissionBuilder.show();
        }
    }

    // 开始提交请求权限
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }

    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else
                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限
    private void showDialogTipUserGoToAppSettting() {

        new android.support.v7.app.AlertDialog.Builder(this)
                .setTitle("读取短信不可用")
                .setMessage("请在-应用设置-权限-中，允许app使用存储权限来保存用户数据")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }

    private void login1(String devicesId, final String AndroidId, HttpXUtils.MyCallback myCallback) {
        Log.d(TAG, "login------------> AndroidId :" + AndroidId + " devicesId: " + devicesId);
        LoginManager.getInstance().login1(this, devicesId, AndroidId, myCallback);
    }

    private void getTheBoundBank1(String phoneNumber, HttpXUtils.MyCallback myCallback) {
        Log.e(TAG, "getTheBoundBank------------> phoneNumber :" + phoneNumber);
        LoginManager.getInstance().getTheBoundBank1(this, phoneNumber, myCallback);
    }


    /**
     * 获取该手机号绑定的银行
     */
    private void activityFindBackInfo() {
        getTheBoundBank1(Utils.getPhoneNoBySerial(this, Constants.phoneSub1), new HttpXUtils.MyCallback() {
            @Override
            public void myResult(String result) {
                Log.e(TAG, "activityFindBackInfo phoneSub1 success " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray array = jsonObject.getJSONArray("data");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);
                        Constants.hashMap.put(object.optString("name"), object.optString("id"));
                    }
                    Log.e("银行列表", "bankNmeNum:" + array.length());
                    firstBoo = false;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void activityLogin() {
        String url = IPUtils.getOutNetIP(this);
        Log.d(TAG, "-----------------------------------" + url);
        androidId = Utils.getSerialNumber();
        if (androidId.toLowerCase().equals("unknown")) {
            androidId = Utils.getIMEI(this);
        }
        deviceid = Utils.getIMEI(this);
        Log.d(TAG, "login -------------> androidId = " + androidId);
        Log.d(TAG, "login -------------> deviceid = " + deviceid);
        xUtilsLogin();
    }

    private void xUtilsLogin() {
        login1(deviceid, androidId, new HttpXUtils.MyCallback() {
            @Override
            public void myResult(String result) {
                Log.d(TAG, "login success " + result);
                Utils.save2SP(CardStackActivity.this, Constants.LOGIN_SP, androidId, deviceid);
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(result);
                    final String message = jsonObject.optString("message");
                    final String code = jsonObject.optString("code");
                    Log.d(TAG, "LOGIN onFailed = " + code + "------------- MSG=" + message);
                    if (!TextUtils.isEmpty(message) && message.equals("没有权限")) {
                        String tempId = Utils.getDeviceIdFromSp(CardStackActivity.this, androidId);
                        Log.d(TAG, "login -------------> tempId = " + tempId);
                        CardStackActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                urlDialog = new UrlDialog(CardStackActivity.this, UrlHandler, message);
                                if (!urlDialog.isShowing()) {
                                    urlDialog.show();
                                }
                            }
                        });
                    } else if (!TextUtils.isEmpty(message) && message.equals("成功") || message.contains("用户已验证")) {
                        CardStackActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(CardStackActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        CardStackActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                urlDialog = new UrlDialog(CardStackActivity.this, UrlHandler, message);
                                if (!urlDialog.isShowing()) {
                                    urlDialog.show();
                                }
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initPhoneSP() throws JSONException {
        if (ActivityCompat.checkSelfPermission(CardStackActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            requestPermission();
            return;
        }
        Constants.simPhoneNo1 = "";
        Constants.simPhoneNo2 = "";

        Log.d(TAG, "----------------getSystemModel----------------->" + Utils.getSystemModel());
        Log.d(TAG, "----------------getDeviceBrand----------------->" + Utils.getDeviceBrand());

        simArray = SimUtils.getSimInfoBySubscriptionManager(this);
        Log.d(TAG, "initPhoneSP simArray = " + simArray);
        String spSimNo;
        String spSimNo2;
        Constants.isDulCard = false;
        if (simArray.length() > 0) {
            Constants.numbers.clear();
            if (simArray.length() == 1) {
                Constants.phoneSub1 = simArray.getJSONObject(0).optString(Constants.SUBSCRIBER_ID);
                try {
                    Constants.simPhoneNo1 = simArray.getJSONObject(0).optString(Constants.LINE1NUMBER);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (TextUtils.isEmpty(Constants.simPhoneNo1)) {
                    if (isSan) {
                        spSimNo = Constants.sanPhoneNo1;

                    } else {
                        spSimNo = Utils.getPhoneNoBySerial(this, Constants.phoneSub1);
                    }
                } else {
                    spSimNo = Constants.simPhoneNo1;
                }
                Log.d(TAG, "initPhoneSP spSimNo = " + spSimNo);
                if (!TextUtils.isEmpty(spSimNo)) {
                    Utils.saveSimSerial(this, Constants.phoneSub1, spSimNo);
                    Constants.numbers.put(Constants.TEL1_KEY, spSimNo);
                    closeTelDialog();
                } else {
                    showTelDialog(simArray);
                }

            } else if (simArray.length() == 2) {
                Constants.isDulCard = true;
                try {
                    Constants.simPhoneNo1 = simArray.getJSONObject(0).optString(Constants.LINE1NUMBER);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Constants.simPhoneNo2 = simArray.getJSONObject(1).optString(Constants.LINE1NUMBER);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (TextUtils.isEmpty(Constants.simPhoneNo1)) {
                    if (isSan) {
                        spSimNo = Constants.sanPhoneNo1;
                    } else {
                        Constants.phoneSub1 = simArray.getJSONObject(0).optString(Constants.SUBSCRIBER_ID);
                        spSimNo = Utils.getPhoneNoBySerial(this, Constants.phoneSub1);
                    }
                } else {
                    Constants.phoneSub1 = simArray.getJSONObject(0).optString(Constants.SUBSCRIBER_ID);
                    spSimNo = Constants.simPhoneNo1;
                }

                if (TextUtils.isEmpty(Constants.simPhoneNo2)) {
                    if (isSan) {
                        spSimNo2 = Constants.sanPhoneNo2;
                    } else {
                        Constants.phoneSub2 = simArray.getJSONObject(1).optString(Constants.SUBSCRIBER_ID);
                        spSimNo2 = Utils.getPhoneNoBySerial(this, Constants.phoneSub2);
                    }
                } else {
                    Constants.phoneSub2 = simArray.getJSONObject(1).optString(Constants.SUBSCRIBER_ID);
                    spSimNo2 = Constants.simPhoneNo2;
                }

                Log.d(TAG, "initPhoneSP spSimNo = " + spSimNo);
                Log.d(TAG, "initPhoneSP spSimNo2 = " + spSimNo2);
                if (!TextUtils.isEmpty(spSimNo)) {
                    Utils.saveSimSerial(this, Constants.phoneSub1, spSimNo);
                    Constants.numbers.put(Constants.TEL1_KEY, spSimNo);
                }
                if (!TextUtils.isEmpty(spSimNo2)) {
                    Utils.saveSimSerial(this, Constants.phoneSub2, spSimNo2);
                    Constants.numbers.put(Constants.TEL2_KEY, spSimNo2);
                }
                if (TextUtils.isEmpty(spSimNo) || TextUtils.isEmpty(spSimNo2)) {
                    showTelDialog(simArray);
                } else {
                    closeTelDialog();
                }
            }
        } else {
            closeTelDialog();
            showSimErrorDialog();
        }
    }

    private void showSimErrorDialog() {
        new AlertDialog.Builder(this)
                .setTitle("sim卡错误")
                .setMessage("未检测出sim卡，请插入sim卡后再试。")
                .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        System.exit(0);
                    }
                }).setCancelable(true).show();
    }

    private void showTelDialog(JSONArray array) {
        if (telDialog == null) {
            telDialog = new TelDialog(this);
        }
        if (!telDialog.isShowing()) {
            telDialog.show();
        }
    }

    private void showTelDialog() {
        if (telDialog == null) {
            telDialog = new TelDialog(this);
        }
        if (!telDialog.isShowing()) {
            telDialog.show();
        }
    }

    private void closeTelDialog() {
        Log.d(TAG, "--------------closeTelDialog-------------");

        try {
            if (telDialog != null && telDialog.isShowing()) {
                telDialog.dismiss();
                telDialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onItemExpend(boolean expend) {
        Log.d(TAG, "onItemExpend expend = " + expend);
        mActionButtonContainer.setVisibility(expend ? View.VISIBLE : View.GONE);
        versionTv.setVisibility(expend ? View.GONE : View.VISIBLE);
        if (expend) {
            try {
                initPhoneSP();
                //                activityFindBackInfo();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(CardStackActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }
}
